import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import { Table, Menu, Popconfirm, message } from 'antd';


import postActions from '../action'
import appActions from '../../app/action'
import termActions from '../../term/action'
import PostForm from './PostForm';

export class PostDetail extends Component {

  state = {
    termlist : []
  }

  constructor (props) {
    super(props);
  }

  componentWillReceiveProps (props) {

    if(props.params._id && this.props.params._id != props.params._id){
      this.getPostDetail(props.params._id);
    }
  }

  componentDidMount () {

    const {appActions, termActions, postActions} = this.props;
    appActions.loading(true).then(()=>{
      return termActions.getList({type:'post'});
    }).then((doc)=>{
      this.setState({
        termlist : doc.termlist
      });
      appActions.loading(false);
    }).catch(err=>{
      message.error(err.msg);
    });

    console.log(this.props.params._id);

    this.getPostDetail(this.props.params._id);
  }

  /**
   * 获取文章详情
   */
  getPostDetail (_id) {
    const {appActions, termActions, postActions} = this.props;
    postActions.getDetail({_id:_id});
  }

  /**
   * 提交文章表单
   * @param formdata
   */
  handlePostSubmit (formdata) {
    const {postActions, router} = this.props;
    if(this.props.params._id){
      formdata._id = this.props.params._id;
      postActions.postEditPost(formdata).then(data=>{
        postActions.getList({page:1}).then(data=>{
          router.push({
            pathname: 'post'
          });
        })
      }).catch(err=>{
        typeof err.msg == 'object' ?
          message.error(err.msg.message) :
          message.error(err.msg);
      });
    }else{
      postActions.postAddPost(formdata).then(data=>{
        postActions.getList({page:1}).then(data=>{
          router.push({
            pathname: 'post'
          });
        })
      }).catch(err=>{
        message.error(err.msg);
      });
    }
  }

  render() {
    const postdetail = this.props.post.get('postdetail');
    return (
      <div>
        <PostForm
          formValues={postdetail}
          termlist={this.state.termlist}
          handleOK={this.handlePostSubmit.bind(this)}
        />
      </div>
    )
  }

}

export default connect((state)=>{
  return  {
    post : state.get('post')
  }
},dispatch => {
  return {
    postActions : bindActionCreators(postActions, dispatch),
    appActions : bindActionCreators(appActions, dispatch),
    termActions : bindActionCreators(termActions, dispatch),
  }
})(PostDetail);
